<template>
  <div class="order-tab-bar" ref="tabBarRef">
    <!-- 左：可滚动的 Tab 区 -->
    <div class="tab-container" ref="containerRef">
      <div
        class="tab-scroll-wrapper"
        ref="scrollWrapper"
        @scroll="updateOverflowTabs"
        @wheel="handleWheel"
        @keydown="handleKeydown"
        tabindex="0"
      >
        <div class="tab-list" ref="tabList">
          <div
            v-for="tab in tabs"
            :key="tab.key"
            class="tab-item"
            :class="{ 'tab-active': state.activeTab === tab.key }"
            @click="handleTabClick(tab.key)"
          >
            <span class="tab-label">{{ tab.label }}</span>
            <span class="tab-count">({{ tab.count }})</span>
          </div>
        </div>
      </div>

      <!-- 隐藏测量容器：仅用于计算总宽度 -->
      <div class="tab-measure" ref="measureList" aria-hidden="true">
        <div v-for="tab in tabs" :key="tab.key" class="tab-item">
          <span class="tab-label">{{ tab.label }}</span>
          <span class="tab-count">({{ tab.count }})</span>
        </div>
      </div>
    </div>

    <!-- 右侧操作 -->
    <div class="action-buttons" :class="{ 'has-overflow': state.hasMore }">
      <!-- 更多按钮（仅在溢出时显示） -->
      <div
        v-if="state.hasMore"
        class="more-button"
        @mouseenter="handleMoreButtonEnter"
        @mouseleave="handleMoreButtonLeave"
      >
        <div class="more-dots">
          <span></span>
          <span></span>
          <span></span>
        </div>
      </div>

      <el-button type="primary" @click="$emit('batch-dispatch')">批量派单</el-button>
      <el-button type="primary" plain @click="$emit('order-assignment')">订单分配</el-button>
    </div>

    <!-- 更多下拉：展示"当前视口外"的项 -->
    <div
      v-if="showMoreMenu && state.hasMore"
      class="more-menu"
      :style="moreMenuStyle"
      @mouseenter="showMoreMenu = true"
      @mouseleave="handleMoreMenuLeave"
    >
      <div v-for="tab in state.overflowTabs" :key="tab.key" class="more-menu-item" @click="handleTabClick(tab.key)">
        <div class="more-menu-tab-label">{{ tab.label }}</div>
        <div class="more-menu-tab-count">({{ tab.count }})</div>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted, onBeforeUnmount, watch, nextTick } from "vue";

  /** -------- props / emits（JS） -------- */
  const props = defineProps({
    tabs: { type: Array, default: () => [] },
    activeTab: { type: String, default: "" },
  });
  const emit = defineEmits(["tab-change", "batch-dispatch", "order-assignment"]);

  /** 为模板解构（避免到处写 props.xxx） */
  const tabs = props.tabs;

  /** -------- refs -------- */
  const containerRef = ref(null);
  const scrollWrapper = ref(null);
  const tabList = ref(null);
  const measureList = ref(null);
  const tabBarRef = ref(null);

  /** -------- state -------- */
  const state = reactive({
    activeTab: props.activeTab || (props.tabs[0] && props.tabs[0].key) || "",
    hasMore: false,
    overflowTabs: [], // 视口外的项（用于“更多”列表）
  });
  const showMoreMenu = ref(false);
  const moreMenuStyle = ref({});

  /** -------- methods -------- */

  function handleTabClick(key) {
    state.activeTab = key;
    emit("tab-change", key);
    showMoreMenu.value = false;
    nextTick(() => {
      scrollIntoView(key); // 点击后滚到可见并居中
      updateOverflowTabs(); // 同步「更多」列表
    });
  }

  /** 计算更多菜单位置 */
  function calculateMoreMenuPosition() {
    const tabBarEl = tabBarRef.value;
    if (!tabBarEl) return;

    const rect = tabBarEl.getBoundingClientRect();
    moreMenuStyle.value = {
      position: "fixed",
      top: `${rect.bottom - 10}px`,
      right: `${window.innerWidth - rect.right + 195}px`,
      zIndex: 10000,
    };
  }

  /** 更多按钮鼠标进入处理 */
  function handleMoreButtonEnter() {
    calculateMoreMenuPosition();
    showMoreMenu.value = true;
  }

  // 处理更多按钮的鼠标离开事件
  function handleMoreButtonLeave() {
    // 延迟隐藏，给用户时间移动到弹窗
    setTimeout(() => {
      if (!showMoreMenu.value) return; // 如果弹窗已经隐藏，不执行
      // 检查鼠标是否在弹窗区域内
      const menu = document.querySelector(".more-menu");
      if (menu && menu.matches(":hover")) {
        return; // 鼠标在弹窗上，不隐藏
      }
      showMoreMenu.value = false;
    }, 100);
  }

  // 处理弹窗的鼠标离开事件
  function handleMoreMenuLeave() {
    // 延迟隐藏，给用户时间移动回按钮
    setTimeout(() => {
      if (!showMoreMenu.value) return; // 如果弹窗已经隐藏，不执行
      // 检查鼠标是否在按钮区域内
      const button = document.querySelector(".more-button");
      if (button && button.matches(":hover")) {
        return; // 鼠标在按钮上，不隐藏
      }
      showMoreMenu.value = false;
    }, 100);
  }

  /** 处理鼠标滚轮横向滚动 */
  function handleWheel(event) {
    const wrap = scrollWrapper.value;
    if (!wrap) return;

    // 检查是否还有滚动空间
    const canScrollLeft = wrap.scrollLeft > 0;
    const canScrollRight = wrap.scrollLeft < wrap.scrollWidth - wrap.clientWidth;

    // 如果没有横向滚动空间，不阻止默认行为
    if (!canScrollLeft && !canScrollRight) return;

    // 阻止默认的垂直滚动
    event.preventDefault();

    // 获取滚轮滚动量，转换为横向滚动
    const delta = event.deltaY || event.deltaX || 0;
    const scrollAmount = delta * 0.8; // 调整滚动速度，更平滑

    // 执行横向滚动
    wrap.scrollLeft += scrollAmount;

    // 更新溢出状态
    updateOverflowTabs();
  }

  /** 处理键盘按键 */
  function handleKeydown(event) {
    const wrap = scrollWrapper.value;
    if (!wrap) return;

    const scrollAmount = 100; // 每次滚动的距离

    switch (event.key) {
      case "ArrowLeft":
        event.preventDefault();
        wrap.scrollLeft -= scrollAmount;
        updateOverflowTabs();
        break;
      case "ArrowRight":
        event.preventDefault();
        wrap.scrollLeft += scrollAmount;
        updateOverflowTabs();
        break;
      case "Home":
        event.preventDefault();
        wrap.scrollLeft = 0;
        updateOverflowTabs();
        break;
      case "End":
        event.preventDefault();
        wrap.scrollLeft = wrap.scrollWidth - wrap.clientWidth;
        updateOverflowTabs();
        break;
    }
  }

  /** 把指定 key 的 tab 滚动到视口中并尽量居中 */
  function scrollIntoView(key) {
    const wrap = scrollWrapper.value;
    const list = tabList.value;
    if (!wrap || !list) return;
    const items = Array.from(list.children);
    const idx = props.tabs.findIndex(t => t.key === key);
    if (idx < 0 || !items[idx]) return;
    const el = items[idx];
    const targetLeft = el.offsetLeft - (wrap.clientWidth - el.clientWidth) / 2;
    wrap.scrollTo({ left: Math.max(0, targetLeft), behavior: "smooth" });
  }

  /** 判断是否溢出，并计算“当前视口外”的项 */
  function updateOverflowTabs() {
    const wrap = scrollWrapper.value;
    const list = tabList.value;
    if (!wrap || !list) return;

    // 是否溢出：内容总宽 > 容器宽
    state.hasMore = list.scrollWidth > wrap.clientWidth + 1;

    // 计算视口外的项（左右两侧不可见）
    const wrapRect = wrap.getBoundingClientRect();
    const items = Array.from(list.children);
    const outside = [];
    items.forEach((el, i) => {
      const r = el.getBoundingClientRect();
      if (r.right > wrapRect.right + 1 || r.left < wrapRect.left - 1) {
        outside.push(props.tabs[i]);
      }
    });
    // 去重（理论上不需要，这里保险）
    state.overflowTabs = outside.filter((t, i, arr) => arr.findIndex(x => x.key === t.key) === i);
  }

  /** 初始/尺寸变化时：只负责判断溢出与更新 overflow 列表 */
  function recompute() {
    // 用隐藏测量容器测总宽，避免因可见区域压缩导致误判
    const wrap = scrollWrapper.value;
    const measureEl = measureList.value;
    if (!wrap || !measureEl) return;
    const totalWidth = measureEl.scrollWidth;
    state.hasMore = totalWidth > wrap.clientWidth + 1;
    updateOverflowTabs();
  }

  /** -------- observers & watchers -------- */
  let ro = null;
  onMounted(async () => {
    await nextTick();
    recompute();

    ro = new ResizeObserver(() => recompute());
    if (containerRef.value) ro.observe(containerRef.value);
    if (scrollWrapper.value) ro.observe(scrollWrapper.value);
  });
  onBeforeUnmount(() => {
    if (ro) ro.disconnect();
    ro = null;
  });

  // tabs 数据变化（名称/计数）重算
  watch(
    () => props.tabs,
    async () => {
      await nextTick();
      recompute();
    },
    { deep: true }
  );
  // 外部 activeTab 变化时同步并滚动到位
  watch(
    () => props.activeTab,
    async v => {
      state.activeTab = v;
      await nextTick();
      scrollIntoView(v);
    }
  );
</script>

<style scoped lang="scss">
  .order-tab-bar {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    border-bottom: 1px solid var(--cb1);
    height: 62px;
    margin-bottom: 16px;
    background: var(--bg);
    position: relative;
  }

  /* 左侧容器：相对定位，更多按钮吸右 */
  .tab-container {
    position: relative;
    flex: 1;
    min-width: 0;
    display: flex;
    align-items: center;
    margin-bottom: 6px;
  }

  /* 横向滚动区域 */
  .tab-scroll-wrapper {
    flex: 1;
    overflow-x: auto;
    overflow-y: visible; /* 允许垂直方向显示横线 */
    -ms-overflow-style: none;
    scrollbar-width: none;
    scroll-behavior: smooth; /* 平滑滚动 */
    cursor: grab; /* 鼠标悬停时显示抓取手势 */
    &:active {
      cursor: grabbing; /* 拖拽时显示抓取手势 */
    }
    &::-webkit-scrollbar {
      display: none;
    }
  }
  .tab-list {
    display: flex;
    align-items: center;
    gap: 24px;
    padding-bottom: 8px; /* 为底部横线留出空间 */
    min-width: max-content;
  }

  /* 单个 Tab */
  .tab-item {
    display: flex;
    align-items: center;
    gap: 2px;
    padding: 0px 8px 4px 8px;
    border-radius: 6px;
    cursor: pointer;
    white-space: nowrap;
    flex-shrink: 0;
    &.tab-active {
      position: relative;
      &::after {
        content: "";
        position: absolute;
        bottom: -8px;
        left: 50%;
        transform: translateX(-50%);
        width: 24px;
        height: 4px;
        background: var(--bd);
        border-radius: 2px;
      }
    }
  }
  .tab-label {
    font-size: 16px;
    font-weight: 400;
    color: var(--ct2);
  }
  .tab-count {
    font-size: 12px;
    font-weight: 400;
    color: var(--ct2);
  }

  /* 选中状态的文字样式 */
  .tab-item.tab-active {
    .tab-label {
      font-size: 16px;
      font-weight: 600;
      color: var(--ct1);
    }
    .tab-count {
      font-size: 12px;
      font-weight: 600;
      color: var(--ct1);
    }
  }

  /* 隐藏测量容器：不可见但可测量 */
  .tab-measure {
    position: fixed;
    visibility: hidden;
    z-index: -1;
    left: -9999px;
    top: -9999px;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  /* 更多按钮与菜单 */
  .more-button {
    width: 24px;
    height: 24px;
    margin-right: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: color 0.2s ease;

    &:hover {
      color: var(--bd);
    }
  }

  .more-dots {
    display: flex;
    align-items: center;
    gap: 2px;

    span {
      width: 3px;
      height: 3px;
      border-radius: 50%;
      background-color: currentColor;
      transition: background-color 0.2s ease;
    }
  }
  .more-menu {
    width: auto;
    padding-top: 4px;
    background: var(--bg);
    border: 1px solid var(--cb1);
    border-radius: 4px;
    box-shadow: 0 0 6px 0 #0000001f;

    /* 添加小三角指示器 */
    &::before {
      content: "";
      position: absolute;
      z-index: -1;
      top: -6px;
      right: 20px;
      width: 12px;
      height: 10px;
      background: var(--bg);
      border: 1px solid var(--cb1);
      border-bottom: none;
      border-right: none;
      transform: rotate(45deg);
    }
  }
  .more-menu-item {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    gap: 4px;
    padding: 10px 16px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 600; // 默认正常粗细
    color: var(--ct1);
    // transition: all 0.2s ease; // 添加平滑过渡
    // 方法1: 使用letter-spacing来预留空间
    // letter-spacing: 0.1px;

    &:hover {
      cursor: pointer;
      background: var(--fl1);
      color: var(--bd);
      font-weight: 600; // hover时加粗
      // 方法2: 调整letter-spacing来补偿宽度变化
      letter-spacing: 0;

      .more-menu-tab-label {
        color: var(--bd);
      }

      .more-menu-tab-count {
        color: var(--bd);
      }
    }
  }

  /* 右侧操作 */
  .action-buttons {
    display: flex;
    align-items: center;
    flex-shrink: 0;
    position: relative;
    height: 100%;
    /* 左侧渐变效果 - 仅在溢出时显示 */
    &.has-overflow::before {
      content: "";
      position: absolute;
      left: -6px;
      top: 0;
      width: 6px;
      height: 100%;
      background: linear-gradient(270deg, #f2f1f5 0%, rgba(255, 255, 255, 0) 100%);
      pointer-events: none;
    }
  }
</style>
